<template>
	<view class="content">
		<view class="safe-area-top" />
		<!-- 自定义导航栏 -->
		<view class="custom-nav">
			<view class="back-btn" @tap="goBack">
				<text class="icon">←</text>
			</view>
			<text class="title">初识</text>
		</view>
		<view class="total-info">
			<text>总计: {{currentIndex}}/10</text>
		</view>
		<scroll-v scroll-y class="stage-scroll">
			<view class="uni-margin-wrap">
				<view>
					<view class="chat-img">
						<image :src="scene_image_url" mode="widthFix"></image>
						<view class="chat-bubble">
							<text>{{user_question}}</text>
						</view>
					</view>
				</view>
				<view class="options-section">
					<view v-for="(option, optionIndex) in options" :key="optionIndex" class="btn-wrapper">
						<button :class="{'custom-btn': true, 'btn-active':activeStus[optionIndex] }"
							hover-class="is-hover"
							@click="handleOptionClick(currentIndex, optionIndex)">{{option}}</button>
					</view>
				</view>
			</view>
		</scroll-v>
		<!-- 底部按钮 -->
		<view class="bottom-btn">
			<button class="light-btn" @click="handleLightClick">
				<image class="light-icon" src="/static/tip_icon.png" mode="widthFix"></image>
			</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		fetchUserDetail
	} from '../../api/detail'
	const currentIndex = ref(0)
	const selectedOption = ref(null)
	const isCorrectAnswer = ref(false)
	const progress_id = ref(null)
	const user = ref({})
	const questionList = ref([])
	const isActive = ref(false)
	const isShowAn = ref(false)
	const systemInfo = uni.getSystemInfoSync();
	const screenHeight = ref(0);
	const user_question = ref('')
	const options = ref([])
	const activeStus = ref([false, false, false])
	const content_id = ref(0)
	const selectedText = ref('')
	const user_id = ref(1)
	const scene_id = ref(0)
	const character_id = ref(0)
	const scene_image_url = ref('')


	onLoad((options) => {
		console.log('cqw------id =' + options.id + "scene_id = " + options.scene_id + 'currentIndex = ' + options.index)
		// progress_id.value = options.id
		user_id.value = 1
		character_id.value = options.id
		scene_id.value = options.scene_id
		currentIndex.value = options.index
		gameProgress()
	})

	async function loadChat() {
		uni.showLoading({
			title: '加载中...',
			mask: true
		});
		try {
			const url = `https://test.r.ads.sohu.com/api/v1/game/generate-stage/${progress_id.value}`;
			console.log('cqw url = ' + url)
			const res = await uni.request({
				url: url,
				method: 'POST',
				timeout: 30000
			});
			currentIndex.value++
			user_question.value = res.data.data.user_question
			content_id.value = res.data.data.id
			scene_image_url.value = res.data.data.scene_image_url
			console.log('res.data:', res.data);
			options.value = res.data.data.options
			console.log('请求成功:', res.data.data);
		} catch (err) {
			console.error('loadChat 请求失败:', err);
		} finally {
			uni.hideLoading(); // 无论成功或失败都隐藏 loading
		}
	}

	async function submitChoice() {
		try {
			const url = `https://test.r.ads.sohu.com/api/v1/game/submit-choice/${content_id.value}`;
			console.log('cqw url = ' + url + 'selectedOption='+ selectedOption.value + 'selectedText='+ selectedText.value)
			const response = await uni.request({
				url: url,
				method: 'POST',
				data: {

					choice_index: selectedOption.value,
					choice_text: selectedText.value
				},
			});
			console.info('submitChoice 提交完成',response.data);
			console.info(response.data);
			
			console.info('submitChoice 提交完成', response.data.data.stage_content);
			// content_id.value = response.data.data.stage_content.id
			console.log('cqw+++ handleLightClick currentIndex= ',currentIndex.value)
			
			if (currentIndex.value > 10) {
				console.log('cqw+++ handleLightClick ')
				uni.navigateTo({
					url: "../result/result?id=${progress_id.value}"
				});
			} else {
				loadChat()
			}

		} catch (err) {

			// 显示错误提示
			uni.showToast({
				title: '提交失败，请重新提交',
				icon: 'none', // 不显示图标，只显示文字
				duration: 60000
			});
			console.error('submitChoice 请求失败:', err.message);
		} finally {
			// 	uni.hideLoading(); // 无论成功或失败都隐藏 loading
		}
	}

	async function gameProgress() {
		try {
			const url = `https://test.r.ads.sohu.com/api/v1/game/progress`;
			console.log('cqw url = ' + url)
			const res = await uni.request({
				url: url,
				method: 'POST',
				data: {
					user_id: 1,
					character_id: character_id.value,
					scene_id: scene_id.value
				},
			});
			progress_id.value = res.data.data.id
		
			console.info('gameProgress 请求完成 ', res,'id=',res.data.data.id);
			
			loadChat()

		} catch (err) {
			console.error('gameProgress 请求失败:', err);
		} finally {
			
		}
	}

	onMounted(() => {
		const {
			windowHeight
		} = uni.getSystemInfoSync();
		screenHeight.value = windowHeight;
		// console.log('cqw+++ height = ' + windowHeight)

		fetchData()
	})
	// 处理选项点击
	function handleOptionClick(questionIndex, optionIndex) {
		selectedOption.value = optionIndex
		selectedText.value = options.value[optionIndex]
console.info("options ="+options.value + 'questionIndex = ' + questionIndex + 'optionIndex = ' + optionIndex)
		// 2秒后自动跳到下一题
		if (questionIndex <= 10) {
			submitChoice()
			// setTimeout(() => {
			// 	currentIndex.value = ++currentIndex.value;

			// 	resetQuestionState()
			// }, 2000)
		} else {
			uni.showToast({
				title: '已经是最后一页'
			});
		}
	}

	function handleLightClick() {
		console.log('cqw+++ handleLightClick ')
		uni.navigateTo({
			url: "../result/result"
		});
	}


	function goBack() {
		uni.navigateBack()
	}
	// 模拟请求数据
	async function fetchData() {
		// const res = await uni.request({ url: 'https://api.xxx.com/ai-user-list' })
		// userList.value = res.data.data
		// 模拟接口延迟
		await new Promise(resolve => setTimeout(resolve, 500))
		// mock 数据
		questionList.value = [{
				answerIndex: 2,
				options: ['2岁。', '关你屁事！', '2岁了，你家的呢？'],
				speechText: 'Hi 你家小狗好可爱，多大了',
				image: '/static/logo.png'
			},
			{
				image: '/static/logo.png',
				speechText: '这花真好看，哪买的',
				options: ['路边摘的', '花店买的', '朋友送的'],
				answerIndex: 1

			},
			{
				image: '/static/logo.png',
				speechText: '最后一题问题',
				options: ['选项A', '选项B', '选项C'],
				answerIndex: 0
			}
		]
	}
</script>

<style scoped>
	.safe-area-top {
		/* padding-top: env(safe-area-inset-top); */
		height: 50px;
	}

	.custom-nav {
		display: flex;
		align-items: center;
		height: 44px;
		background-color: #fff;
		border-bottom: 1px solid #f2f2f2;
		padding: 0 15px;
	}

	.back-btn {
		display: flex;
		align-items: center;
	}

	.icon {
		font-size: 20px;
		color: #000;
	}

	.title {
		flex: 1;
		text-align: center;
		font-size: 17px;
		font-weight: bold;
		margin-top: 20rpx;
		padding: 20rpx 20rpx 20rpx 20rpx;
	}

	/* 总计信息样式 */
	.total-info {
		margin-top: 15px;
		font-size: 16px;
		color: #f00;
		/* 红色，可根据实际需求调整 */
		text-align: center;

	}

	.custom-btn {
		line-height: 1.2;
		font-size: 14px;
		/* 配合行高，设置合适的字体大小 */
		/* 其他样式，比如背景色、边框等，可按需添加 */
		background-color: #f5f5f5;
		border: 1px solid #ddd;
		padding: 10px;
		border-radius: 6px;
	}


	.uni-margin-wrap {
		width: 100%;
		height: 100%;
		overflow: hidden;
		padding: 20rpx 20rpx 20rpx 20rpx;
		/* 左右各20rpx间距 */
		box-sizing: border-box;
	}

	.total {
		justify-content: center;
		align-items: center;
		display: flex;
	}

	.chat-img {
		display: inline-block;
		width: 100%;
		position: relative;
		/* background-color: bisque; */
		height: 200rpx;
	}

	.chat-img image {
		width: 100%;
		height: 100%;
		border-radius: 8rpx;
	}

	.options-section {
		/* 	  display: flex */
		flex-direction: column;
		gap: 40px;
		width: 100%;
		margin-top: 10px;
	}

	.btn-wrapper {
		margin-bottom: 20rpx;
		/* 垂直间距20rpx */
	}

	/* .option-btn {
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 4px;
  text-align: left;
  padding: 10px;
} */
	.chat-bubble {
		position: absolute;
		top: 10px;
		left: 40rpx;
		right: 40rpx;
		/* transform: translateX(-10%); */
		background-color: rgba(255, 255, 255, 0.8);
		padding: 8px 12px;
		border-radius: 15px;
		font-size: 14px;
		color: #333;

	}

	.bottom-btn {
		/* 固定定位，使按钮始终在屏幕右下角 */
		position: fixed;
		bottom: 40rpx;
		right: 15rpx;
		border-radius: 10rpx;
	}

	.light-btn {
		background-color: white;
		border-radius: 10rpx;
		border: none;
		color: #e69837;
		/* padding: 5px; */
	}

	.light-icon {
		width: 20px;
		height: 20px;
	}

	.is-hover {
		/* color: rgba(255, 255, 255, 0.6); */
		background-color: red;
		border-color: #179b16;
	}

	/* 选中状态 */
	.btn-active {
		background-color: red;
		color: red;
		/* 选中时的背景色 */
	}
</style>